package com.atguigu.day22.refltct05.r1;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class PersonTest {

    @Test
    public void test05() {
    //获取class对象
        Class<Person> personClass = Person.class;
        //获取指定的构造器
        //getDeclaredConstructors->调用所有构造器
        //getConstructors->只能调用public构造器
        Constructor<?>[] constructors = personClass.getDeclaredConstructors();
        //遍历所有构造器
        for (Constructor<?> cons : constructors){
            System.out.println("cons = " + cons);
        }
    }

    @Test
    public void test04() throws Exception {
        //todo 私有的构造器
        //1.获取Class对象
        Class<?> aClass = Class.forName("com.atguigu.reflect05.r1.Person");
        //2.获取指定的构造器Declare
        Constructor<?> constructor = aClass.getDeclaredConstructor(String.class, int.class, double.class);
        //3.禁止java语法访问检查
        constructor.setAccessible(true);

        //4.给成员变量赋值
        Object o = constructor.newInstance("李四", 20, 1.89);
        //5.展示对象
        System.out.println("o = " + o);


    }

    @Test
    public void test03() throws Exception {
        //1.获取Class对象
        Class<Person> personClass = Person.class;
        //2.获取指定的构造器
        Constructor<Person> constructor = personClass.getConstructor(String.class, int.class, double.class, double.class);

        //3.给成员变量赋值
        Person person = constructor.newInstance("张三", 20, 1.78, 99999.5);

        //4.展示对象
        System.out.println("person = " + person);

    }


    @Test
    public void test02() throws Exception {
        //1.获取Class对象
        Class<?> aClass = Class.forName("com.atguigu.reflect05.r1.Person");

        //2.获取指定的构造器
        Object o = aClass.newInstance();
        System.out.println("o = " + o);
    }


    @Test
    public void test01() {
        //1.获取Class对象
        Class<Person> personClass = Person.class;
        //2.获取构造器
        //获取公共的构造器
        //  Constructor<?>[] constructors = personClass.getConstructors();
        //获取所有的构造器
        Constructor<?>[] constructors = personClass.getDeclaredConstructors();

        for (Constructor<?> c : constructors) {
            System.out.println("c = " + c);
        }
    }
}
